package com.jason.session;

import com.jason.config.BoundSql;
import com.jason.config.MapperStatement;
import com.jason.util.ParameterMapping;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BaseStatementHandler implements StatementHandler {

    @Override
    public PreparedStatement parameterHand(Connection connection, MapperStatement mapperStatement, BoundSql boundSql, Object ... params)
            throws SQLException, IllegalAccessException, NoSuchFieldException {
        String prepareSql = boundSql.getParseSql();
        System.out.println("预编译sql:" + prepareSql);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        Class<?> parameterType = mapperStatement.getParameterType();

        //SQL预编译处理
        PreparedStatement preparedStatement = connection.prepareStatement(prepareSql);
        //设置参数值
        for (int i = 1; i <= parameterMappings.size(); i ++) {
            String name = parameterMappings.get(i - 1).getContent();
            //反射
            Field declareField = parameterType.getDeclaredField(name);
            declareField.setAccessible(true);
            //参数设置值
            Object value = declareField.get(params[0]);
            System.out.print("参数值：" + value + "\t");
            preparedStatement.setObject(i, value);
        }
        System.out.println();
        return preparedStatement;
    }


    @Override
    public <E> List<E> resultHand(ResultSet resultSet, MapperStatement mapperStatement)
            throws SQLException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
        Class<?> resultClass = mapperStatement.getResultType();
        List<E> resultList = new ArrayList<>();
        //封装返回的结果
        while (resultSet.next()) {
            E o = (E) resultClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int cloumnCount = metaData.getColumnCount();
            for(int i = 1; i <= cloumnCount ; i ++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                //创建属性描述器，为属性生成读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
                //获取写方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                //向类中写入值
                writeMethod.invoke(o, value);
            }
            resultList.add(o);
        }
        return resultList;
    }


}
